package android.explorer;
import java.io.File;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.explorer.activity.FileCopy;
import android.explorer.dialogUltility.ShowOkDialog;
import android.explorer.dialogUltility.ShowYesNoDialog;
import android.explorer.interfaces.CallBack;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Explorer extends Activity{
	final int properpties=0x00000;
	final int delete=0x0022;
	ListView list;
	boolean create=false;
	String lastPath="",selectPath;
	boolean isCopy=true;
	TextView tv;
	int select=-1;
	private String currentPath="/";
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int a=0;
        try{
        	setContentView(R.layout.main); 
	        list=(ListView)findViewById(R.id.list);
	        tv=(TextView)findViewById(R.id.current);
	        ((Button)findViewById(R.id.goup)).setOnClickListener(new View.OnClickListener() {
	             public void onClick(View v) {
	            	String parent=getParent(currentPath);
	     	    	if(parent!=null)
	     	    	list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(parent)));
	             }
	         });
	       
	        list.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
				public void onItemSelected(AdapterView<?> arg0, View v,
						int arg2, long arg3) {
					selectPath=((ViewHolder)v.getTag()).getFilePath();
					select=arg2;
				}
				public void onNothingSelected(AdapterView<?> arg0) {
					selectPath=null;
					select=-1;
				}
	          });
	        list.setAdapter(new DirectoryAdapter(this,getChild("/")));
	        list.setOnItemClickListener(new OnItemClickListener() {
	   		 public void onItemClick(AdapterView<?> a, View v, int position, long id) {
	   			String path="";
	   			 try{
	   				ViewHolder item = (ViewHolder)v.getTag();
	   				path=item.getFilePath();
	   				if(path==null)return;
	   				System.out.println(!new File(path).isFile());
	   				if(!new File(path).isFile())
	   					list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(path)));
	   				else{
	   					actionOpen(path);
	   				}
	   	        }catch(Exception e){
	   	        }
	   		 }
	   		});
        }catch(Exception e){
        	Toast.makeText(this, "Error :  "+e.getMessage()+a, Toast.LENGTH_LONG).show();
        }
        }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)){
	    	if(currentPath.equals("/"))System.exit(0);
	    	String parent=getParent(currentPath);
	    	if(parent==null)return true;
	    	list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(parent)));
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
    private String getParent(String path){
    	return new File(path).getParent();
    }
    private String getInfor(File file){
    	try{
    	if(file.isFile()){
    		return "File size : "+file.length()+" b";
    	}else{
    		if(file.list()==null)return "Directory is empty";
    		return "Items cont : "+file.list().length+".";
    	}
    	}catch(Exception e){
    		return e.toString();
    	}
    }
    public FileItem[] getChild(String parent){
    	tv.setText("Current : "+parent);
		FileItem[] item=null;
		currentPath=parent;
		File file=new File(parent);
		String list[]=file.list();
		if(list==null){
			item=new FileItem[1];
			item[0]=new FileItem(false,false,"(Directory is empty)",null,"Nothing here","empty");
		}else{
			item=new FileItem[list.length];
			for(int i=0;i<list.length;i++){
				File a=new File(currentPath+"/"+list[i]);
				item[i]=new FileItem(true,a.isFile(),a.getName(),currentPath+"/"+a.getName(),getInfor(a),null);//a.getPath());
			}
		}
		return item;
	}
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, menu);
        return true;
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	actionRefresh();
    }
    public boolean onOptionsItemSelected(MenuItem item){
    	switch(item.getItemId()){
    	case R.id.copy:
    		if(select==-1)break;
    		actionCopy();
    		break;
    	case R.id.exit:
    		System.exit(0);
    		break;
    	case R.id.rename:
    		actionRename();
    		break;
    	case R.id.refresh:
    		actionRefresh();
    		break;
    	case R.id.createfolder:
    		actionCreateFolder();
    		break;
    	case R.id.goup:
    		String parent=getParent(currentPath);
 	    	if(parent!=null)
 	    	list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(parent)));
 	    	break;
    	case R.id.cut:
    		if(select==-1)break;
    		actionCut();
    		break;
    	case R.id.gotoDesktop:
    		list.setAdapter(new DirectoryAdapter(this,getChild("/")));
    		break;
    	case R.id.paste:
    		actionPaste();
    		break;
    	case R.id.delete:
    		actionDelete();
    		break;
    	case R.id.properties:
    		actionProperties();
    		break;
    	case R.id.about:
    		actionAout();
    		break;
    	}
    	return true;
    }
    private void actionRefresh(){
    	list.setAdapter(new DirectoryAdapter(this,getChild(currentPath)));
    }
    private void actionAout(){
    	Intent intent=new Intent(Explorer.this,android.explorer.activity.FormAbout.class);
		startActivityForResult(intent,delete);	
    }
    private void actionOpen(String path){
    	MimeTypeMap tMimeType = MimeTypeMap.getSingleton();
    	String tMimeStr = tMimeType.getMimeTypeFromExtension(path.substring(path.length()-3).toLowerCase());
    	System.out.println(path.substring(path.length()-3));
		Intent intent=new Intent();
		Uri data = Uri.parse("file://"+path);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(data,tMimeStr);
		try {
			startActivity(intent);
		} catch (Exception e) {
			Toast.makeText(this, "Can not find any program associate with this file.",Toast.LENGTH_LONG).show();
		}
    }
    private void actionDelete(){
    	if(selectPath==null){
    		new ShowOkDialog(this,"You must select a item before continue.","Information",null);
    		return;
    	}
    	final File file=new File(selectPath);
    	if(file.isFile()){
	    	new ShowYesNoDialog(this,"Are you sure want to delete the file "+selectPath+" ?","Confirm delete",new OnClickListener(){
				public void onClick(DialogInterface arg0, int arg1) {
					System.out.println("Sap xoa");
					if(file.delete()){
						Toast.makeText(Explorer.this, "Delete this file has finished successfully !", Toast.LENGTH_LONG).show();
					}else{
						Toast.makeText(Explorer.this, "Delete this file has finished failed !", Toast.LENGTH_LONG).show();
					}
					list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(currentPath)));
					
				}
	    	});
    	}else{
    		new ShowYesNoDialog(this,"Are you sure want to delete the file "+selectPath+" ?","Confirm delete",new OnClickListener(){
				public void onClick(DialogInterface arg0, int arg1) {
					Intent intent=new Intent(Explorer.this,android.explorer.activity.FolderDelete.class);
					intent.putExtra("foldername", selectPath);
		    		startActivityForResult(intent,delete);	
				}
	    	});
    	}
    }
    private void actionRename(){
    	final File file=new File(selectPath);
    	new InputBox(this,"Enter new name !",file.getName(),new CallBack(){
			public void onOKClick() {}
			public void onOkClick(String value) {
				if(value!=null){
					try{
						File fileto=new File(file.getParent()+"/"+value);
						
						if(fileto.exists()){
							Toast.makeText(getApplicationContext(), "This name has been used by another file.", Toast.LENGTH_LONG).show();
						}else if(file.renameTo(fileto)){
							Toast.makeText(getApplicationContext(), "Renaming is successly.", Toast.LENGTH_LONG).show();
						}else{
							Toast.makeText(getApplicationContext(), "Renaming is failed.", Toast.LENGTH_LONG).show();
						}
					}catch(Exception e){
						Toast.makeText(getApplicationContext(), "Error "+e.getMessage(), Toast.LENGTH_LONG).show();
					}
				}
				list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(currentPath)));
			}
    	}).show();
    }
    private void actionProperties(){
    	String selectPath=this.selectPath;
    	if(selectPath==null)selectPath=this.currentPath;
    	File file=new File(selectPath);
    	if(file.isFile()){
	    	Intent intent=new Intent(this,android.explorer.activity.FileProperties.class);
			intent.putExtra("filename",selectPath);
			startActivityForResult(intent,properpties);
    	}else{
    		Intent intent=new Intent(this,android.explorer.activity.FolderProperties.class);
    		intent.putExtra("foldername",selectPath);
			startActivityForResult(intent,properpties);
    	}
    }
    private void actionCreateFolder(){
    	new InputBox(this,"Enter the folder's name","",new CallBack(){
			public void onOKClick() {}
			public void onOkClick(String value) {
				if(value!=null){
					try{
						File file=new File(currentPath+"/"+value);
						if(file.exists()){
							Toast.makeText(getApplicationContext(), "This folder already exit.", Toast.LENGTH_LONG).show();
						}else if(file.mkdir()){
							Toast.makeText(getApplicationContext(), "Creating folder is successly.", Toast.LENGTH_LONG).show();
						}else{
							Toast.makeText(getApplicationContext(), "Creating folder is failed.", Toast.LENGTH_LONG).show();
						}
					}catch(Exception e){
						Toast.makeText(getApplicationContext(), "Error "+e.getMessage(), Toast.LENGTH_LONG).show();
					}
				}
				list.setAdapter(new DirectoryAdapter(Explorer.this,getChild(currentPath)));
			}
    	}).show();
    }
    private void actionCopy(){
    	if(selectPath==null)return;
		if(new File(selectPath).isFile())
			Toast.makeText(this, "The file "+selectPath +" will copy when you select command paste.", Toast.LENGTH_SHORT).show();
		else Toast.makeText(this, "The folder "+selectPath +" will copy when you select command paste.", Toast.LENGTH_SHORT).show();
		lastPath=selectPath;
		isCopy=true;
    }
    private void actionCut(){
		if(selectPath==null)return;
		if(new File(selectPath).isFile())
			Toast.makeText(this, "The file "+selectPath +" will move when you select command paste.", Toast.LENGTH_SHORT).show();
		else Toast.makeText(this, "The folder "+selectPath +" will move when you select command paste.", Toast.LENGTH_SHORT).show();
		lastPath=selectPath;
		isCopy=false;
    }
    private void actionPaste(){
    	if(lastPath==""){
    		Toast.makeText(this, "You must select a file or a folder and call command copy or cut before.", Toast.LENGTH_LONG).show();
    		return;
    	}
    	File src=new File(lastPath);
    	if(src.getParent()==currentPath){
    		Toast.makeText(this, "The dest folder is'n vaild.\nPlease select another folder.",Toast.LENGTH_LONG ).show();
    		return;
    	}
    	if(currentPath.indexOf(lastPath)>=0){
    		Toast.makeText(this, "The dest folder is'n vaild.\nPlease select another folder.",Toast.LENGTH_LONG ).show();
    		return;
    	}
    	if(isCopy){
    		Intent intent=new Intent(this,FileCopy.class);
    		intent.putExtra("filesource", lastPath);
    		intent.putExtra("folderdes", currentPath+"/"+src.getName());
    		startActivityForResult(intent, 0x000111);
    	}else{
    		File f1=new File(lastPath);
    		File f2=new File(currentPath+"/"+f1.getName());
    		try {
				if(f1.renameTo(f2)){
					Toast.makeText(this, "Operation has finished successfuly", Toast.LENGTH_LONG).show();
				}else{
					Toast.makeText(this, "Operation has finished failed", Toast.LENGTH_LONG).show();
				}
			} catch (Exception e) {
				Toast.makeText(this, "Error when execute the  command "+e.toString()+".", Toast.LENGTH_LONG).show();
				e.printStackTrace();
			}
    	}
    	actionRefresh();
    }
    public void onSdcardButtonClick(View target){
    	list.setAdapter(new DirectoryAdapter(Explorer.this,getChild("/mnt/sdcard")));
	}
}
